<template>
  <div>
    <!-- <a-spin tip="读取中" class="editor-spinner" v-if="showLoading">
    </a-spin> -->
    <a-layout>
      <a-layout-header :style="headerStyle">
        <div class="page-title">
          <router-link to="/">
            <img alt="Vue logo" src="../../assets/logo-simple.png" class="logo-img">
          </router-link>
          <inline-edit v-if="pageState.title" class="edit-area" :value="pageState.title" @change="titleChange">
          </inline-edit>
        </div>
        <div class="right-col">
          <a-menu :selectable="false" theme="dark" mode="horizontal"
            :style="{ lineHeight: '64px', justifyContent: 'end' }">
            <a-menu-item key="1">
              <a-button type="primary" @click="previewWork">预览和设置</a-button>
            </a-menu-item>
            <a-menu-item key="2">
              <a-button type="primary" @click="saveWork(true)" :loading="saveIsLoading">保存</a-button>
            </a-menu-item>
            <a-menu-item key="3">
              <a-button type="primary" @click="publishWorkFn" :loading="isPublishing">发布</a-button>
            </a-menu-item>
            <a-menu-item key="4">
              <user-profile :user="userInfoStore" :smMode="true"></user-profile>
            </a-menu-item>
          </a-menu>
        </div>
      </a-layout-header>
      <a-layout class="main-layout">
        <a-layout-sider :style="siderStyle">
          <div class="sidebar-container">组件列表</div>
          <a-tabs v-model:activeKey="materialTabKey" size="large">
            <a-tab-pane key="1">
              <template #tab>
                <i class="iconfont icon-string"></i>
                文本
              </template>
              <ComponentList type="l-text" :list="defaultTextTemplates" @on-item-click="addItem"></ComponentList>
            </a-tab-pane>
            <a-tab-pane key="2">
              <template #tab>
                <i class="iconfont icon-tupian"></i>
                图片
              </template>
              <ComponentList type="l-image" :list="defaultImageTemplates" @on-item-click="addItem"></ComponentList>
            </a-tab-pane>
            <a-tab-pane key="3">
              <template #tab>
                <i class="iconfont icon-tetris02"></i>
                形状
              </template>
              形状
            </a-tab-pane>
          </a-tabs>
          <img id="test-image" />
        </a-layout-sider>
        <a-layout-content class="preview-container">
          <p>画布区域</p>
          <history-area></history-area>
          <div class="preview-list" :class="{ 'canvas-fix': canvasFix }" id="canvas-area">
            <div class="body-container" :style="state.page.props">
              <div v-for="v in state.components" :key="v.id">
                <editor-wrapper v-if="!v.isHidden" :id="v.id" :props="v.props"
                  :active="v.id === state.currentElement?.id" @update-position="updatePosition" @set-active="setActive">
                  <component :is="v.name" v-bind="v.props" :isEditing="true"></component>
                </editor-wrapper>
              </div>
            </div>
          </div>
        </a-layout-content>
        <a-layout-sider width="300" style="background: #fff" class="settings-panel">
          <a-tabs type="card" v-model:activeKey="activePanel">
            <a-tab-pane key="component" tab="属性设置" class="no-top-radius">
              <div v-if="state.currentElement">
                <div v-if="!state.currentElement.isLocked">
                  <edit-group v-if="state.currentElement && state.currentElement.props"
                    :props="state.currentElement.props" @change="handleChange">
                  </edit-group>
                </div>
                <div v-else>
                  <a-empty>
                    <template #description>
                      <p>该元素被锁定，无法编辑</p>
                    </template>
                  </a-empty>
                </div>
              </div>
              <div v-else>
                <a-empty>
                  <template #description>
                    <p>在画布中选择元素并开始编辑</p>
                  </template>
                </a-empty>
              </div>
            </a-tab-pane>
            <a-tab-pane key="layer" tab="图层设置">
              <layer-list :list="state.components" :selectedId="state.currentId" @select="(id) => { setActive(id) }"
                @change="handleChange">
              </layer-list>
              <br />
              <!--             <layer-list-demo :list="state.components" :selectedId="state.currentId" @select="(id) => { setActive(id) }"
              @change="handleChange">
            </layer-list-demo> -->
            </a-tab-pane>
            <a-tab-pane key="page" tab="页面设置">
              <props-table @change="pageChange" :props="state.page.props"></props-table>
            </a-tab-pane>
          </a-tabs>
        </a-layout-sider>
      </a-layout>
      <a-layout-footer :style="footerStyle">Footer</a-layout-footer>
    </a-layout>

    <a-modal title="发布成功" v-model:open="showModal" width="700px" :footer="null">
      <channel-form v-if="showModal" />
    </a-modal>
    <preview-form
      v-if="showPreviewForm"
      :visible="showPreviewForm"
      @onClose="showPreviewForm=false"
      :isSaving="saveIsLoading"
      :isPublishing = "isPublishing"
      @trigger-publish="publishWorkFn"
      @trigger-save="saveWork(true)"
      ></preview-form>
  </div>
</template>

<script setup lang="ts">
import { defineAsyncComponent, computed, reactive, ref, onMounted, onUnmounted, type CSSProperties, nextTick } from 'vue'
import { editorInfos } from '@/stores/editor'
import defaultTextTemplates, { defaultImageTemplates } from '@/constant/defaultTemplates'
import pinia from '@/stores/index'
import EditorWrapper from '@/components/EditWrapper.vue'
import PropsTable from '@/components/PropsTable.vue'
import LayerList from '@/components/LayerList.vue'
import EditGroup from '@/components/EditGroup.vue'
import HistoryArea from './HistoryArea.vue'
import { pickBy, mapValues } from 'lodash-es'
import initHotKeys from '@/plugins/hotKeys'
export type TabType = 'component' | 'layer' | 'page'
import initContextMenu from '@/plugins/initContextMenu'
import UserProfile from '@/components/UserProfile.vue'
import { userInfos } from '@/stores/user'
import { gloabl } from '@/stores/global'
import { useRoute } from 'vue-router';
import InlineEdit from '@/components/InlineEdit.vue'
import useSaveWork from '@/hooks/useSaveWork'
import ChannelForm from './ChannelForm.vue'
import usePublishWork from '@/hooks/usePublishWork'
import PreviewForm from './PreviewForm.vue'

  const globalStore = gloabl(pinia)
  const editorStore = editorInfos(pinia)
  const route = useRoute()


  const footerStyle: CSSProperties = {
    textAlign: 'center',
    color: '#fff',
    backgroundColor: '#001529'
  }

  const userInfoStore = userInfos(pinia)


initContextMenu()
initHotKeys()
const {saveWork, saveIsLoading} = useSaveWork()
const { publishWork, isPublishing } = usePublishWork()
const ComponentList = defineAsyncComponent(() => import('@/components/ComponentList.vue'))

const materialTabKey = ref('2')
const activePanel = ref<TabType>('component')
const canvasFix = ref(false)
const showModal = ref(false)
const showPreviewForm = ref(false)


const addItem = (component: ComponentData) => {
  editorStore.addComponent(component)
}

const state = reactive({
  currentId: computed(()=>editorStore.currentElement),
  currentElement: computed(() => editorStore.getCurrentElement()),
  components: computed(()=>editorStore.components),
  page: computed(()=>editorStore.page)
})

const pageState = computed(() => editorStore.page)

const titleChange = (newTitle: string) => {
  editorStore.updatePage({ key: 'title', value: newTitle })
  nextTick(() => {
    saveWork()
  })
}
const previewWork = async() => {
  await saveWork()
  showPreviewForm.value = true
}



const publishWorkFn = async()=>{
  editorStore.setActive('')
  const el = document.getElementById('canvas-area') as HTMLElement
  canvasFix.value = true
  await nextTick()
/*   html2canvas(el, {width:375,useCORS:true, scale: 1}).then(canvas=>{
    const image = document.getElementById('test-image') as HTMLImageElement
    image.src = canvas.toDataURL()
    canvasFix.value = false
  }) */

  try {
    publishWork(el)
  } catch (e) {
    console.log(e)
  } finally{
    canvasFix.value = false
    isPublishing.value = false
    showModal.value = true
    showPreviewForm.value = false
  }
}

const handleChange = (e: any) => {
  editorStore.updateComponent(e)
}
const pageChange =(e:any)=>{
  editorStore.updatePage({ ...e, level: 'props' })
}
const setActive = (id: string) => {
  editorStore.setActive(id)
}
const updatePosition=(data: {left:number; top: number;id:string})=>{
  const { id } = data
  const newPair = mapValues(pickBy(data, (v, k) => k !== 'id'), (value) => {
    return value + 'px'
  })
  const keysArr = Object.keys(newPair)
  const valuesArr = Object.values(newPair)
  editorStore.updateComponent({ key: keysArr , value: valuesArr, id} )
}

const headerStyle: CSSProperties = {
  textAlign: 'center',
  height: 64,
  paddingInline: 50,
  lineHeight: '64px',
};

const contentStyle: CSSProperties = {
  textAlign: 'center',
  minHeight: 120,
  lineHeight: '120px',
  backgroundColor: '#108ee9',
};

const siderStyle: CSSProperties = {
  backgroundColor: '#fff',
  padding: '0 10px'
};




</script>

<style lang="scss" scoped>

.header {
  display: flex;
  justify-content: space-between;
}
.header .logo-img {
  margin-right: 20px;
  height: 40px;
}
.page-title {
  display: flex;
  align-items: center;
}
  .ant-layout-header {
    z-index: 50;
    box-shadow: 0 10px 15px rgba(0, 0, 0, .1);
    display: flex;
    justify-content: space-between;
  }
  
  .transparent-header {
    background-color: rgba(0, 0, 0, .5)
  }
  
  .home-layout {
    position: relative;
    top: -70px;
  }

  .header .logo-img {
    height: 35px;
  }
  
  .header .ant-input-search {
    width: 250px;
  }
  
  .right-col{
    flex: 1 1 auto;
    >* {
        margin-left: 30px !important;
       
      }
  }
  .editor-spinner {
    position: fixed;
    right: 50%;
    top: 10px;
    z-index: 100;
  }
 .preview-container {
  padding: 10px 24px;
  margin: 0;
  min-height: 85vh;
  display: flex;
  flex-direction: column;
  align-items: center;
  position: relative;
  height: calc(100vh - 134px);
}

.preview-list {
  padding: 0;
  margin: 0;
  min-width: 375px;
  min-height: 200px;
  border: 1px solid #efefef;
  background: #fff;
  overflow-x: hidden;
  overflow-y: auto;
  position: fixed;
  margin-top: 50px;
  max-height: 80vh;
  &.canvas-fix {
    position: absolute;
    max-height: none;
    .edit-wrapper > * {
      box-shadow: none !important;
    }
  }
}
.preview-list.active {
  border: 1px solid #1890ff;
}

.sidebar-container {
  padding: 20px;
}
.body-container {
  width: 100%;
  height: 100%;
  background-size: cover;
}
</style>
